package cn.udrm.water.base.v1.commons.config;

import lombok.Getter;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@Configuration
@Getter
@Setter
public class Swagger2Config extends WebMvcConfigurationSupport {
	
	@Value("${swagger.project.base.url}")
	private String PROJECT_BASE_URL;
	@Value("${swagger.site.base.url}")
	private String SITE_BASE_URL;

	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
		registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
		registry.addResourceHandler("/public/**").addResourceLocations("classpath:/public/");
		registry.addResourceHandler("swagger-ui.html")
		    .addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**")
		    .addResourceLocations("classpath:/META-INF/resources/webjars/");
		super.addResourceHandlers(registry);
    }
	
	@Bean
	public Docket createWaterdistributeRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.host(SITE_BASE_URL)
				.apiInfo(apiInfo())
				.groupName("WaterDistributeRestApi")
				.select()
				.apis(RequestHandlerSelectors.basePackage("cn.udrm.water.base.v1.waterdistribute.restful"))
				.paths(PathSelectors.any())
				.build();
	}
	@Bean
    public Docket createWaterdeliveryRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
        		.host(SITE_BASE_URL)
                .apiInfo(apiInfo())
                .groupName("WaterDeliveryRestApi")
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.udrm.water.base.v1.waterdelivery.restful"))
                .paths(PathSelectors.any())
                .build();
    }
	
	private ApiInfo apiInfo() {
		if (StringUtils.isBlank(PROJECT_BASE_URL)) {
			this.PROJECT_BASE_URL = "http://localhost:8080";
		}
        return new ApiInfoBuilder()
                .title("灌排基础数据Restful API 文档")
                .description("项目主页，" + this.PROJECT_BASE_URL)
                .termsOfServiceUrl(this.PROJECT_BASE_URL)
                .version("1.0")
                .build();
    }
}
